package org.funtester.performance.books.chapter05.sectioin2;

import org.funtester.performance.books.chapter03.common.ThreadTool;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

/**
 * WebSocket客户端示例
 */
public class WebSocketClinetDemo {

    public static void main(String[] args) throws URISyntaxException {
        String uri = "ws://localhost:12345/websocket";// 服务端地址
        URI serverUri = new URI(uri);// 转换为URI
        WebSocketClient webSocketClient = new WebSocketClient(serverUri) {// 创建WebSocket客户端

            /**
             * 连接打开时候调用的方法
             * @param serverHandshake
             */
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                System.out.println("连接打开");
                serverHandshake.iterateHttpFields().forEachRemaining(x -> System.out.println("握手信息  key: " + x + " value: " + serverHandshake.getFieldValue(x)));
            }

            /**
             * 收到消息时候调用的方法
             * @param s
             */
            @Override
            public void onMessage(String s) {
                System.out.println("收到消息: " + s);
            }

            /**
             * 连接关闭时候调用
             * @param i
             * @param s
             * @param b
             */
            @Override
            public void onClose(int i, String s, boolean b) {
                System.out.println("连接关闭,code码: " + i + ",原因: " + s + ",是否由远程服务关闭: " + b);
                close();// 关闭连接
            }

            /**
             * 出错时候调用
             * @param e
             */
            @Override
            public void onError(Exception e) {
                System.out.println("连接异常");
                e.printStackTrace();// 打印异常堆栈信息
                close(1, "客户端异常关闭");// 关闭连接
            }

            /**
             * 关闭连接
             */
            @Override
            public void close() {
                super.close();
                System.out.println("连接关闭");
            }

        };
        System.out.println("连接中...");
        webSocketClient.addHeader("name", "FunTester");// 添加请求头
        webSocketClient.addHeader("password", "123456");// 添加请求头
        webSocketClient.removeHeader("password");// 移除请求头
        webSocketClient.connect();// 建立WebSocket连接
        int retryCount = 0;// 重试次数
        while (true) {
            if (retryCount++ > 3) {// 判断重试次数
                System.out.println("连接失败");
                break;
            }
            ThreadTool.sleep(1000);// 等待1秒
            if (webSocketClient.isOpen()) {// 判断是否连接成功
                System.out.println("WebSocket客户端状态: " + webSocketClient.getReadyState().name());
                break;
            }
        }
        System.out.println("连接成功");
        webSocketClient.send("Hello WebSocket!");// 发送消息
        webSocketClient.sendPing();// 发送Ping消息

    }

}
